import 'dart:convert';

import 'package:flutter_app/bean/center_data_entity.dart';
import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/network/UploadFilesUtils.dart';
import 'package:flutter_app/ui/mine/accumulate_points/accumulate_points_view.dart';
import 'package:flutter_app/ui/mine/film/film/film_view.dart';
import 'package:flutter_app/ui/mine/my_apply/my_apply_view.dart';
import 'package:flutter_app/ui/mine/set/set_view.dart';
import 'package:flutter_app/utils/ImagePickersUtils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:get/get.dart';

import 'mine_state.dart';

class MineLogic extends GetxController {
  final MineState state = MineState();

  // 下拉框内容
  List<String> yearItems = [];

  // 当前默认显示的 list的索引
  int currentIndex = 0;

  // 当前下拉框内容
  var year = "";

  @override
  void onInit() {
    super.onInit();
    state.userInfo = UserInfoManager().getUserInfo();
  }

  @override
  void onReady() {
    super.onReady();
    postCenterData();
  }

  /// 获取个人中心数据
  Future<void> postCenterData() async {
    Map<String, dynamic> param = {};
    ResultData resultData = await Api.postCenterData(param);
    if (resultData.isSuccess) {
      List<dynamic> list = jsonDecode(jsonEncode(resultData.data['data']));
      state.centerDataEntity = list.map((e) => CenterDataEntity.fromJson(e)).toList();
      initData();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  // 初始化数据
  void initData() {
    yearItems.clear();
    state.centerDataEntity?.forEach((element) {
      yearItems.add(element.year ?? "");
    });
    year = yearItems.first;
    getSignRate();
    getScore();
    getProgressValue();
    update();
  }

  // 刷新数据
  void refreshData(String value) {
    currentIndex = getCurrentIndex(value);
    getSignRate();
    getScore();
    getProgressValue();
    update();
  }

  // 获取任务参与率
  void getSignRate() {
    state.signRate.value = (state.centerDataEntity?[currentIndex].signRate ?? 0).toString() + '%';
  }

  // 获取积分
  void getScore() {
    state.score.value = state.centerDataEntity?[currentIndex].score ?? "0";
  }

  // 获取积分百分比
  void getProgressValue() {
    double score = double.parse(state.centerDataEntity?[currentIndex].score ?? "0");
    score = score > 90 ? 90 : score;
    state.progressValue.value = score / 100;
  }

  // 根据下拉框选择的值，来判断是 list 的索引
  // 返回 -1 表示没有找到
  int getCurrentIndex(value) {
    int index = 0;
    state.centerDataEntity!.forEach((element) {
      if (element.year!.contains(value)) {
        index = state.centerDataEntity!.indexOf(element);
      }
    });
    return index;
  }

  /// 使用相机拍摄上传
  Future<void> openCameraUp() async {
    Media? media = await ImagePickersUtils().openCamera();
    if (media == null) {
      return;
    } else {
      List<Media> list = [];
      list.add(media);
      updateUserAvatar(list);
    }
  }

  /// 使用相册上传
  Future<void> openPhotoUp() async {
    List<Media> list = await ImagePickersUtils().selectImages(selectCount: 1);
    if (list.length == 0) {
      return;
    } else {
      updateUserAvatar(list);
    }
  }

  /// 更新头像
  Future<void> updateUserAvatar(List<Media> imagesList) async {
    if (imagesList.length == 0) {
      return toast.show("图片为空");
    }
    List<FilePathEntity>? filePathEntity = await UploadFilesUtils().uploadFiles(imagesList);
    if (filePathEntity == null) {
      return;
    }
    Map<String, dynamic> param = {
      "avatar": filePathEntity.first.sourcePath, // 头像url地址
      "userId": UserInfoManager().getUserId(), // 用户id
    };

    ResultData resultData = await Api.updateUserAvatar(param);
    if (resultData.isSuccess) {
      state.userInfo?.headUrl = resultData.data["data"]["headUrl"];
      update();
      // 保存信息到本地
      UserInfoManager().setUserInfo(state.userInfo);
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  // 随手拍上报记录
  void goToFilmPage() => Get.to(() => FilmPage(title: "随手拍上报记录"));

  // 我的报名
  void goToMyApply() => Get.to(() => MyApplyPage(title: "我的报名"));

  // 设置
  void goToSetPage() => Get.to(() => SetPage(title: "设置页面"));

  // 积分明细
  void goToAccumulatePointsPage() => Get.to(
        () => AccumulatePointsPage(title: "积分明细"),
        arguments: {
          "yearItems": yearItems,
          "year": year,
        },
      );

  @override
  void onClose() {
    super.onClose();
  }
}
